package dofix;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class EmployeeMaxEnergyFix {

	public static void main(String[] args) throws Exception {
		String url = args[0];
//		jdbc:mysql://rdsd09ffm5143cy22qd4.mysql.rds.aliyuncs.com:3306/platform?characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
		if (!url.startsWith("jdbc:")) {
			url = "jdbc:mysql://" + url + "?characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true";
		}
		String user = args[1];
		String password = args[2];
		Connection conn = DriverManager.getConnection(url, user, password);
		
		try {
			PreparedStatement ps = conn.prepareStatement("select count(id) from employee");
			ResultSet rs = ps.executeQuery();
			int n = 0;
			if (rs.next()) {
				n = rs.getInt(1);
			}
			rs.close();
			ps.close();
			
			int offset = 0;
			while (n > 0) {
				int rows = n > 1000 ? 1000 : n;
				ps = conn.prepareStatement("select id, level, maxEnergy from employee limit ?, ?");
				ps.setInt(1, offset);
				ps.setInt(2, rows);
				rs = ps.executeQuery();
				
				PreparedStatement ps2 = conn.prepareStatement("update employee set maxEnergy = ? where id = ?");
				while (rs.next()) {
					long id = rs.getLong(1);
					int level = rs.getInt(2);
					int maxEnergy = rs.getInt(3);
					
					ps2.setInt(1, level - 1);
					ps2.setLong(2, id);
					ps2.addBatch();
					System.out.println(id + "," + maxEnergy + "->" + (level - 1));
				}
				int[] arr = ps2.executeBatch();
				ps2.close();
				System.out.println("batch:" + (arr != null ? arr.length : 0));
				
				rs.close();
				ps.close();
				
				offset += rows;
				n -= rows;
			}
			
			
		} finally {
			conn.close();
		}
		
	}
	
//	static TemplateService service;
//	static void load(String dataDir) throws Exception {
//		App.getApp().getConfig().put(Config.DATA_DIR, dataDir);
//		service = new TemplateService();
//		TemplateParser parser = new TemplateParser(service);
//		parser.parse(EmployeeTemplate.class);
//	}
	
}
